import { getEnabledElement, utilities as csUtils, VolumeViewport3D } from "@cornerstonejs/core";
import * as cornerstoneTools from "@cornerstonejs/tools";

const { BaseTool } = cornerstoneTools;

export default class VolumeShiftColorTool extends BaseTool {
	static toolName;
	constructor(
		toolProps = {},
		defaultToolProps = {
			supportedInteractionTypes: ["Mouse", "Touch"]
		}
	) {
		super(toolProps, defaultToolProps);
	}

	touchDragCallback(evt) {
		this.mouseDragCallback(evt);
	}

	mouseDragCallback(evt) {
		const { element, deltaPoints } = evt.detail;
		const enabledElement = getEnabledElement(element);
		const { viewport } = enabledElement;
		// console.log("mouseDragCallback", viewport, deltaPoints.canvas[1]);
		if (viewport instanceof VolumeViewport3D) {
			const { preset } = viewport.getProperties();
			let shiftPos = preset.shiftPos || 0;

			const yDelta = deltaPoints.canvas[1] * -1;
			shiftPos += yDelta;

			this._shiftVRColor(viewport, preset, shiftPos);
		}
	}

	_shiftVRColor(viewport, preset, pos) {
		// console.log("_shiftVRColor pos:", pos);

		const volumeActor = viewport.getDefaultActor().actor;

		const color = preset.colorTransfer.split(" ").map(Number);
		for (let i = 1; i < color.length; i += 4) {
			color[i] = color[i] + pos;
		}

		// const newColor = color.join(" ");
		// console.log("new color:", newColor);

		const opacity = preset.scalarOpacity.split(" ").map(Number);
		for (let i = 1; i < opacity.length; i += 2) {
			opacity[i] = opacity[i] + pos;
		}

		// const newOpacity = opacity.join(" ");
		// console.log("new opacity:", newOpacity);

		const newPreset = { ...preset };
		newPreset.colorTransfer = color.join(" ");
		newPreset.scalarOpacity = opacity.join(" ");

		preset.shiftPos = pos;

		csUtils.applyPreset(volumeActor, newPreset);
		viewport.render();
	}
}

VolumeShiftColorTool.toolName = "VolumeShiftColor";
